package com.amiba.crm.admin.service.impl;

import cn.hutool.core.util.StrUtil;
import com.amiba.crm.admin.domain.entity.QuartzEntity;
import com.amiba.crm.admin.mapper.QuartzMapper;
import com.amiba.crm.admin.service.QuartzService;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.quartz.*;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 任务调度信息业务逻辑层
 * Create By HZI.HUI
 * 2019/8/1 15:02
 */
@Service
@AllArgsConstructor
@Slf4j
public class QuartzServiceImpl extends ServiceImpl<QuartzMapper, QuartzEntity> implements QuartzService {

    private final QuartzMapper quartzMapper;
    private final Scheduler scheduler;

    /**
     * 获取任务调度的数量
     * @param map
     * @return
     */
    @Override
    public int queryQuartzCount(Map<String, Object> map) {
        return quartzMapper.queryQuartzCount(map);
    }

    /**
     * 任务分页数据
     * @param quartz
     * @param page
     * @return
     */
    @Override
    public IPage queryQuartzList(QuartzEntity quartz, Page page) {
        return quartzMapper.queryQuartzList(page,quartz);
    }


    /**
     * 添加任务
     * @param quartz 任务实体
     * @return
     */
    @Override
    public boolean addTask(QuartzEntity quartz) {
        try {
            //如果是修改  展示旧的 任务
            if(quartz.getOldJobGroup()!=null){
                JobKey key = new JobKey(quartz.getOldJobName(),quartz.getOldJobGroup());
                scheduler.deleteJob(key);
            }
            Class cls = Class.forName(quartz.getJobClassName()) ;
            cls.newInstance();
            //构建job信息
            JobDetail job = JobBuilder.newJob(cls).withIdentity(quartz.getJobName(),
                    quartz.getJobGroup())
                    .withDescription(quartz.getDescription()).build();
            // 触发时间点
            CronScheduleBuilder cronScheduleBuilder = CronScheduleBuilder.cronSchedule(quartz.getCronExpression());
            Trigger trigger = TriggerBuilder.newTrigger().withIdentity("trigger"+quartz.getJobName(), quartz.getJobGroup())
                    .startNow().withSchedule(cronScheduleBuilder).build();
            //交由Scheduler安排触发
            scheduler.scheduleJob(job, trigger);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    /**
     * 删除定时任务
     * @param quartz
     * @return
     */
    @Override
    public boolean removeTask(QuartzEntity quartz){
        try {
            TriggerKey triggerKey = TriggerKey.triggerKey(quartz.getJobName(), quartz.getJobGroup());
            // 停止触发器
            scheduler.pauseTrigger(triggerKey);
            // 移除触发器
            scheduler.unscheduleJob(triggerKey);
            // 删除任务
            scheduler.deleteJob(JobKey.jobKey(quartz.getJobName(), quartz.getJobGroup()));
            System.out.println("removeJob:"+JobKey.jobKey(quartz.getJobName()));
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    /**
     * 更新任务
     * @param quartz 任务实体
     * @return
     */
    @Override
    public boolean updateTask(QuartzEntity quartz){
        try{
            if(quartz.getOldJobGroup()!=null){
                JobKey key = new JobKey(quartz.getOldJobName(),quartz.getOldJobGroup());
                scheduler.deleteJob(key);
            }
            boolean flag = addTask(quartz);
            if(flag){
                return true;
            }
        }catch (Exception e){
            log.error("更新任务失败===>>>{}",e.getMessage());
        }
        return false;
    }

    /**
     * 用药计划cron表达式
     * @param dateNode
     * @param timeNode
     * @return
     */
    @Override
    public String medicinePlanCron(String dateNode, String timeNode) {
        List<String> list = new ArrayList<>();
        String[] dataNode = dateNode.split(",");
        for (int i = 0; i < dataNode.length; i++) {
            switch (dataNode[i]){
                case "周一":
                    list.add("MON");
                    break;
                case "周二":
                    list.add("TUE");
                    break;
                case "周三":
                    list.add("WED");
                    break;
                case "周四":
                    list.add("THU");
                    break;
                case "周五":
                    list.add("FRI");
                    break;
                case "周六":
                    list.add("SAT");
                    break;
                case "周日":
                    list.add("SUN");
                    break;
                default:
                    list.add("MON,TUE,WED,THU,FRI,SAT,SUN");
                    break;
            }
        }
        String[] times = timeNode.split(":");
        return  "0 "+times[1]+" "+times[0]+" ? * "+ StrUtil.join(",",list);
    }


}
